import React, {Component} from 'react';
import moment from 'moment'
import { connect, Dispatch } from 'umi'
import {Card, Button, Table, Modal } from 'antd'

import AddUpdateForm from './component/addOrUpdate'
import { ConnectState } from '@/models/connect';
import { UserManageStateType } from './model'


interface UserManageProps {
  dispatch: Dispatch;
  userManage: UserManageStateType;
  isLoading?: boolean;
}

class Index extends Component<UserManageProps> {
  state = {
    users: [], // 所有用户列表
    roles: [], // 所有角色列表
    isShow: false, // 添加修改弹窗显示
    form: {}, // form方法
    allFields: [
      {
        name: ['username'],
        value: ''
      },{
        name: ['password'],
        value: ''
      },{
        name: ['phone'],
        value: ''
      },{
        name: ['email'],
        value: ''
      },{
        name: ['role_id'],
        value: ''
      },
    ],
  }

  columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    }, {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    }, {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },{
      title: '注册时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (time: Date) => moment(time).format('YYYY-MM-DD hh: mm: ss')
    },{
      title: '所属角色',
      dataIndex: 'role_id',
      key: 'role_id',
      render: (role_id: string) => {
        const { roleNames } = this.props
        return roleNames[role_id]
      }
    },{
      title: '操作',
      key: 'actions',
      render: user => {
        return (
          <>
            <Button onClick={() => this.showUpdate(user)} type="link">修改</Button>
            <Button onClick={() => this.deleteUser(user)} type="link">删除</Button>
          </>
        )
      }
    },
  ];

  showAdd = () => {
    const { dispatch } = this.props
    this.setState({
      isShow: true,
      allFields: [
        {
          name: ['username'],
          value: ''
        },{
          name: ['password'],
          value: ''
        },{
          name: ['phone'],
          value: ''
        },{
          name: ['email'],
          value: ''
        },{
          name: ['role_id'],
          value: ''
        },
      ],
    })
     dispatch({
      type: 'userManage/save',
      payload: {
        user: {}
      }
    })
  };

  showUpdate = (user: any) => {
    const { dispatch } = this.props;
    this.setState({
      isShow: true,
      allFields: [
        {
          name: ['username'],
          value: user.username
        },{
          name: ['password'],
          value: user.password
        },{
          name: ['phone'],
          value: user.phone
        },{
          name: ['email'],
          value: user.email
        },{
          name: ['role_id'],
          value: user.role_id
        },
      ],
    });
    dispatch({
      type: 'userManage/save',
      payload: {
        user
      }
    })
  };

  deleteUser = (user: any) => {
    Modal.confirm({
      title: `确认删除${user.username}吗?`,
      onOk: () => {
        const { dispatch } = this.props;
        dispatch({
          type: 'userManage/fetchDeleteUser',
          payload: {
            userId: user._id
          },
          callback: () => this.getUser()
        })
      }
    })
  };

  getUser = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userManage/fetchUsers',
      payload: {},
      callback: (users: any[], roles: any[]) => {
        this.setState({ users, roles })
      }
    })
  };

  addOrUpdateUser = (): void => {
    const { user, dispatch } = this.props;
    const { form } = this.state;
    this.setState({isShow: false});
    // 1. 收集输入数据;
    const newUser = form.getFieldsValue();
    form.resetFields();
    if (user._id) {
      newUser._id = user._id
    }
    // 2. 提交添加的请求
    dispatch({
      type: 'userManage/fetchAddOrUpdateUser',
      payload: {
        ...newUser
      },
      callback: () => this.getUser()
    })
  };

  onFieldsDataChange = (date?: object) => {
    this.setState({ allFields: date })
  };

  handleModalVisible = (flag?: boolean) => {
    return () => {
      this.setState({
        isShow: !!flag,
      })
    }
  };

  componentDidMount(): void {
    this.getUser()
  }

  render() {
    const { users, isShow, roles, allFields } = this.state;
    const { isLoading } = this.props;
    const title = <Button onClick={this.showAdd} type="primary">创建用户</Button>;
    const allOrUpdate = {
      roles,
      allFields,
      visible: isShow,
      addOrUpdateUser: this.addOrUpdateUser,
      handleModalVisible: this.handleModalVisible,
      onFieldsDataChange: this.onFieldsDataChange,
      setForm: (form: any) => this.setState({form})
    }
    return (
      <Card title={title}>
        <Table
          bordered
          rowKey="_id"
          loading={isLoading}
          dataSource={users}
          columns={this.columns}
          pagination={{
            defaultPageSize: 3,
          }}
        />
        <AddUpdateForm {...allOrUpdate}/>
      </Card>
    );
  }
}

export default connect(({ userManage, loading }: ConnectState) => ({
  ...userManage,
  isLoading: loading.effects['userManage/fetchUsers']
}))(Index);
